package com.xixiake.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.xixiake.R;
import com.xixiake.application.BaseApplication;
import com.xixiake.net.BaseInput;
import com.xixiake.net.GsonRequest;
import com.xixiake.net.NetClient;
import com.xixiake.net.record.RegisterPinCodeRecord;
import com.xixiake.net.record.RegisterVerifyCodeRecord;
import com.xixiake.utils.ToastUtil;
import com.xixiake.utils.VerityUtils;

/**
 * Created by c-wanghengli on 2017/6/3.
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {


    private RelativeLayout mLiearlayout;
    private TextView mLeftTextView;
    private ImageView mImageView;
    private EditText mPhoneEditText;
    private EditText mVerifyCodeEditText;
    private Button mVerifyButton;
    private TextView mProcotolText;
    private CheckBox mAlreadyReadCheckBox;
    private Button mNextButton;
    private Drawable drawable;

    private InputMethodManager manager;
    private BaseApplication mBaseApplication;

    private TimeCount timeCount;
    private String usernumber;
    private String phoneno;
    private String vcode;

    private boolean isSelect = true;
    private int scene = 1;    // 验证使用场景, 具体值为1时表示 : 注册时, 发送验证码, 详见接口文档
    private int errorcode;
    private String errorMsg;

    @Override
    protected void onResume() {
        super.onResume();
        setContentView(R.layout.register_verify);
        init();
        initView();
        initData();
        initEvent();
    }

    private void init() {
        mBaseApplication = (BaseApplication) getApplication();
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
      //  checkMesPermision();
    }

    final int REQUEST_CODE_ASK_PERMISSIONS_FOR_MES = 0;
    private void checkMesPermision() {
        int mesPermision = ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.SEND_SMS);
        if (mesPermision != PackageManager.PERMISSION_GRANTED) {
            //ActivityCompat.shouldShowRequestPermissionRationale低于M版本是false
            if (!ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivity.this, Manifest.permission.SEND_SMS)) {
               ActivityCompat.requestPermissions(RegisterActivity.this, new String[]{Manifest.permission.SEND_SMS}, REQUEST_CODE_ASK_PERMISSIONS_FOR_MES);
            } else {
                ActivityCompat.requestPermissions(RegisterActivity.this, new String[]{Manifest.permission.SEND_SMS}, REQUEST_CODE_ASK_PERMISSIONS_FOR_MES);
            }
        } else {
            registerSmsReceiver();
        }
    }

    private void registerSmsReceiver() {

    }

    private void initView() {
       // super.initView();

        mLiearlayout = (RelativeLayout) findViewById(R.id.common_title);

        mLeftTextView = (TextView) findViewById(R.id.title_left_txt_view);
        drawable = getResources().getDrawable(R.mipmap.btn_arrow_circle_left);

        mImageView = (ImageView) findViewById(R.id.title_right_img_view);

        mPhoneEditText = (EditText) findViewById(R.id.own_register_edit_phone);

        mVerifyCodeEditText = (EditText) findViewById(R.id.own_register_edit_vcode);

        mVerifyButton = (Button) findViewById(R.id.own_register_verify_button);

        mAlreadyReadCheckBox = (CheckBox) findViewById(R.id.own_register_already_protocol);

        mProcotolText = (TextView) findViewById(R.id.own_register_protocol);

        mNextButton = (Button) findViewById(R.id.own_login_button_oklogin);

        timeCount = new TimeCount(60000, 1000);

    }


    /**
     * 定时器
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        /**
         * 倒计时状态
         */
        public void onTick(long millisUntilFinished) {
            mPhoneEditText.setEnabled(false);
            mVerifyButton.setText(millisUntilFinished / 1000 + "秒");
            mVerifyButton.setEnabled(false);
        }

        /**
         * 倒计时完成状态
         */
        public void onFinish() {
            mVerifyButton.setText("验证");
            mPhoneEditText.setEnabled(true);
            mVerifyButton.setEnabled(true);
        }
    }

    private void initData() {
        mLiearlayout.setBackgroundResource(R.color.cl_bg_root);

        mLeftTextView.setText("");
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        mLeftTextView.setCompoundDrawables(drawable, null, null, null);

        mImageView.setVisibility(View.GONE);
    }

    private void initEvent() {

        mPhoneEditText.addTextChangedListener(mPhoneEtTextWatcher);

        mVerifyCodeEditText.addTextChangedListener(mVerifyCodeEtTextWatcher);
        mVerifyCodeEditText.setOnClickListener(this);

        mVerifyButton.setOnClickListener(this);

        mAlreadyReadCheckBox.setOnClickListener(this);

        mProcotolText.setOnClickListener(this);

        mNextButton.setOnClickListener(this);

    }

    /**
     * 手机号码编辑框监听器：下一步按钮和验证码按钮的默认状态（灰底白字），如果密码一致和它们都超过6位就改变状态（红底黑字）
     */
    TextWatcher mPhoneEtTextWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            updateButtonStateForPhoneET();
        }
    };

    /**
     * 验证码按钮的监听器
     */
    TextWatcher mVerifyCodeEtTextWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            updateButtonStateForPhoneCodeET();
        }
    };

    /**
     * 更新按钮的颜色状态（灰色为不可点击，红色为可点击）
     */
    private void updateButtonStateForPhoneCodeET() {

        if (mPhoneEditText.length() == 11 && mVerifyCodeEditText.length() == 6 && isSelect == true) {
            mNextButton.setEnabled(true);
        } else {
            mNextButton.setEnabled(false);
        }
    }

    /**
     * 更新按钮的颜色状态（灰色为不可点击，红色为可点击）
     */
    private void updateButtonStateForPhoneET() {

        // 判断发送验证码编辑框
        if (mPhoneEditText.length() == 11) {  // 手机号码编辑框的长度必须是11位数字
            mVerifyButton.setEnabled(true);
        } else {
            mVerifyButton.setEnabled(false);
        }

        // 判断手机号码编辑框和输入验证码编辑框
        if (mPhoneEditText.length() == 11 && mVerifyCodeEditText.length() == 6 && isSelect == true) {   // 手机号码编辑框的长度必须是11位数字 和 验证码编辑框的长度必须是6位数字
            mNextButton.setEnabled(true);
        } else {
            mNextButton.setEnabled(false);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.own_register_verify_button:
                // 获取编辑框上的手机号码
                usernumber = mPhoneEditText.getText().toString().trim();
                if(!"".equals(usernumber)&& VerityUtils.verityPhoneNo(usernumber)){
                    BaseInput<RegisterVerifyCodeRecord> input = RegisterVerifyCodeRecord.Input.buildInput(usernumber,scene);
                    GsonRequest<RegisterVerifyCodeRecord> request = new GsonRequest<>(input, new Response.Listener<RegisterVerifyCodeRecord>() {
                        @Override
                        public void onResponse(RegisterVerifyCodeRecord response) {
                            errorcode = response.errorCode;
                            errorMsg = response.errorMsg;
                            if(errorcode == 0){
                                ToastUtil.show("验证码发送成功",Toast.LENGTH_SHORT);
                                timeCount.start();
                            }else if(errorcode == 10011){
                                ToastUtil.show("手机号已经被注册过，或被微信绑定过\n请更换手机号",Toast.LENGTH_SHORT);
                            }else if(errorcode == 10013 || errorcode ==2){
                                ToastUtil.show("验证码发送过于频繁",Toast.LENGTH_SHORT);
                            }else{
                                ToastUtil.show("验证码发送失败",Toast.LENGTH_SHORT);
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                           ToastUtil.show("验证码发送失败，请检查网络是否连接",Toast.LENGTH_SHORT);
                        }
                    });
                    NetClient.request(request);
                }else{
                    ToastUtil.show("请输入正确的手机号(提示：11位数字)", Toast.LENGTH_SHORT);
                }
                break;
            case R.id.own_login_button_oklogin:
                mNextButton.setEnabled(false);
                mNextButton.setText(getResources().getString(R.string.own_register_verifying));
                if(mVerifyCodeEditText.length() == 6 && mPhoneEditText.length() == 11 & isSelect == true){
                    phoneno = mPhoneEditText.getText().toString().trim();
                    vcode = mVerifyCodeEditText.getText().toString().trim();
                    BaseInput<RegisterPinCodeRecord> input = RegisterPinCodeRecord.Input.buildInput(phoneno,vcode,scene);
                    GsonRequest<RegisterPinCodeRecord> request = new GsonRequest<>(input, new Response.Listener<RegisterPinCodeRecord>() {
                        @Override
                        public void onResponse(RegisterPinCodeRecord response) {
                            errorcode = response.errorCode;
                            if(errorcode == 0){
                                ToastUtil.show("注册校验成功",Toast.LENGTH_SHORT);
                            }else{
                                ToastUtil.show("注册校验失败",Toast.LENGTH_SHORT);
                                mNextButton.setEnabled(true);
                                mNextButton.setText(getResources().getString(R.string.own_register_button_next));
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            ToastUtil.show("网络连接失败，请检查网络是否连接",Toast.LENGTH_SHORT);
                            mNextButton.setEnabled(true);
                            mNextButton.setText(getResources().getString(R.string.own_register_button_next));
                        }
                    });
                    NetClient.request(request);
                }else{
                   ToastUtil.show("请检查上面3个选项是否符合要求",Toast.LENGTH_SHORT);
                }
                break;
        }
    }
}
